<template>
	<view class="container">
		<!-- 渲染模式切换按钮 -->
		<view style="margin-bottom: 10px; text-align: right;">
			<button size="mini" @tap="toggleRenderMode">{{ useTemplateRender ? '切换为默认渲染' : '切换为模板渲染' }}</button>
		</view>
		<!-- 模板渲染区域 -->
		<rich-text v-if="useTemplateRender && renderedTemplate" :nodes="renderedTemplate" class="template-content"></rich-text>
		
		<!-- 默认视图 - 当模板不可用或未启用模板渲染时显示 -->
		<view v-else>
			<!-- 顶部大图轮播 -->
			<view v-if="imageList.length > 0" class="top-swiper-wrap">
				<swiper class="top-swiper" :indicator-dots="false" :current="current" @change="onSwiperChange">
					<swiper-item v-for="(img, idx) in imageList" :key="idx">
						<image :src="getImageUrl(img.url || img)" class="swiper-image" mode="aspectFill" @tap="previewImage(imageList, idx)" />
					</swiper-item>
				</swiper>
				<view class="img-count">{{current + 1}}/{{imageList.length}}</view>
			</view>
			
			<!-- 文章信息 -->
			<view v-if="article" class="article-header">
				<text class="article-title">{{article.content_title || article.title}}</text>
				<view class="article-meta">
					<text class="meta-item">作者：{{article.content_author || article.author || '未知'}}</text>
					<text class="meta-item">发布时间：{{formatDate(article.content_datetime || article.date)}}</text>
					<text class="meta-item">浏览：{{article.content_hit || article.hit || 0}}</text>
				</view>
			</view>
			
			<!-- 文章描述 -->
			<view v-if="article.content_description || article.descrip" class="article-desc">
				<text class="desc-text">{{article.content_description || article.descrip}}</text>
			</view>
			
			<!-- 图片列表 -->
			<view v-if="imageList.length > 0" class="image-list">
				<image
					v-for="(img, idx) in imageList"
					:key="idx"
					:src="getImageUrl(img.url || img)"
					class="list-image"
					mode="widthFix"
					@tap="previewImage(imageList, idx)"
				/>
			</view>
			
			<!-- 文章内容 -->
			<view v-if="article.content_details || article.contentText" class="article-content">
				<text class="content-title">文章详情</text>
				<rich-text :nodes="article.content_details || article.contentText || '暂无内容'" class="content-text"></rich-text>
			</view>
			
			<!-- 分享按钮 -->
			<!-- <view v-if="article && !loading && !error" class="share-btn-wrap">
				<button class="share-btn" open-type="share">分享给客户查看</button>
			</view> -->
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 空状态 -->
		<view v-if="!loading && !article" class="empty-state">
			<text class="empty-text">文章不存在</text>
		</view>
		
		<!-- 错误状态 -->
		<view v-if="error" class="error-container">
			<text class="error-text">{{error}}</text>
			<button @tap="retry" class="retry-btn">重试</button>
		</view>
	</view>
</template>

<script>
import { articleApi, categoryApi } from '@/api/config';
import templateService from '@/utils/template';
import { shareApi } from '@/api/config';
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { getFullImageUrl } from '@/utils/image';


export default {
	data() {
		return {
			article: null,
			category: null,
			imageList: [],
			recommendArticles: [],
			loading: false,
			error: '',
			current: 0,
			// 模板相关数据
			detailTemplate: '',
			renderedTemplate: '',
			templateLoadStatus: {
				success: false,
				message: ''
			},
			useTemplateRender: true // 新增，是否使用模板渲染
		}
	},
	onLoad(options) {
		
		if (options.id) {
			this.loadArticleDetail(options.id);
		} else {
			console.error('[详情页] 缺少文章ID参数');
			this.error = '缺少文章ID参数';
		}
	},
	onShareAppMessage(object) {
		const defaultTitle = this.article?.title || '文章详情';
		const defaultPath = `/pages/detail/detail?id=${this.article?.id || ''}`;
		const defaultImage = this.getFirstImage(this.article?.content_img || this.article?.litpic) || '';
		const promise = new Promise(async (resolve) => {
			if (!this.article || !this.article.id) {
				resolve({
					title: defaultTitle,
					path: defaultPath,
					imageUrl: defaultImage
				});
				return;
			}
			try {
				const res = await shareApi.create({
					shareType: 'content',
					targetId: this.article.id,
					shareTitle: this.article.title,
					shareDescription: this.article.descrip || this.article.content_description || '',
				});
				if (res.code === 200 && res.data && res.data.shareToken) {
					resolve({
						title: res.data.shareTitle,
						path: `/pages/shared/article?token=${res.data.shareToken}`,
						imageUrl: defaultImage
					});
				} else {
					resolve({
						title: defaultTitle,
						path: defaultPath,
						imageUrl: defaultImage
					});
				}
			} catch (e) {
				resolve({
					title: defaultTitle,
					path: defaultPath,
					imageUrl: defaultImage
				});
			}
		});
		
		return {
			title: defaultTitle,
			path: defaultPath,
			imageUrl: defaultImage,
			promise
		};
	},
	onShareTimeline() {
		const defaultTitle = this.article?.title || '文章详情';
		const defaultImage = this.getFirstImage(this.article?.content_img || this.article?.litpic) || '';
		return {
			title: defaultTitle,
			query: `id=${this.article?.id || ''}`,
			imageUrl: defaultImage
		};
	},
	methods: {
		async loadArticleDetail(id) {
			try {
				this.loading = true;
				this.error = '';
				
				
				const detailRes = await articleApi.getDetail(id);
				
				if (detailRes.code === 200) {
					this.article = detailRes.data;
				
					
					// 获取分类信息
					await this.loadCategory();
					
					// 解析图片数据
					this.parseImages();
					
					// 获取推荐文章
					await this.loadRecommendArticles();
					
					// 加载并渲染模板
					if (this.category) {
						await this.loadTemplate(this.category);
						this.renderTemplate();
					}
				} else {
					console.error('[详情页] API返回错误码:', detailRes.code, '错误信息:', detailRes.msg);
					throw new Error('文章不存在');
				}
				
			} catch (error) {
				console.error('[详情页] 加载失败, 错误详情:', error);
				console.error('[详情页] 错误堆栈:', error.stack);
				this.error = error.message || '文章加载失败';
			} finally {
				this.loading = false;
			}
		},
		
		async loadCategory() {
			// 获取文章所属分类
			const categoryId = this.article.categoryId || this.article.category_id;
			
			if (!categoryId) {
				console.warn('[详情页] 文章没有分类ID');
				return;
			}
			
			try {
				const categoryRes = await categoryApi.getDetail(categoryId);
				
				if (categoryRes.code === 200) {
					this.category = categoryRes.data;
				} else {
					console.warn('[详情页] 获取分类信息失败:', categoryRes.msg);
				}
			} catch (error) {
				console.error('[详情页] 加载分类失败:', error);
			}
		},
		
		// 加载详情模板
		async loadTemplate(category) {
			if (!category) {
				console.warn('[详情页] 没有分类信息，无法加载模板');
				return;
			}
			
			try {
				this.templateLoadStatus = {
					success: false,
					message: '正在加载模板...'
				};
				
				// 加载详情模板
				this.detailTemplate = await templateService.getCategoryDetailTemplate(category);
				
				// 打印模板加载状态
				if (this.detailTemplate) {
					this.templateLoadStatus.success = true;
					this.templateLoadStatus.message = '模板加载成功';
				} else {
					console.warn('[详情页] 模板加载失败或为空');
					this.templateLoadStatus.message = '模板加载失败或为空';
				}
			} catch (error) {
				console.error('[详情页] 加载模板失败:', error);
				this.templateLoadStatus.message = `模板加载错误: ${error.message}`;
			}
		},
		
		// 渲染模板
		renderTemplate() {
			try {
				if (!this.detailTemplate) {
					this.renderedTemplate = '';
					return;
				}
				// 扁平化数据结构，便于 mustache 渲染
				const templateData = {
					...(this.article || {}),
					category: this.category,
					recommendArticles: this.recommendArticles
				};
				// 使用 mustache 渲染
				const rendered = templateService.parseTemplate(this.detailTemplate, templateData);
				if (rendered) {
					this.renderedTemplate = rendered;
				} else {
					this.renderedTemplate = '';
				}
			} catch (error) {
				console.error('[详情页] 模板渲染错误:', error);
				this.renderedTemplate = '';
			}
		},
		
		parseImages() {
			// 解析图片数据
			const imageData = this.article.content_img || this.article.litpic;
			
			if (imageData) {
				try {
					if (typeof imageData === 'string') {
						// 尝试解析JSON格式
						if (imageData.startsWith('[')) {
							this.imageList = JSON.parse(imageData);
						} else {
							// 分隔符格式
							this.imageList = imageData.split(',').map(url => ({url: url.trim()}));
						}
					} else if (Array.isArray(imageData)) {
						this.imageList = imageData;
					} else {
						this.imageList = [];
					}
				} catch (error) {
					console.error('[详情页] 解析图片数据失败:', error);
					console.error('[详情页] 解析失败的错误堆栈:', error.stack);
					this.imageList = [];
				}
			} else {
				this.imageList = [];
			}
		},
		
		async loadRecommendArticles() {
			try {
				const params = {
					categoryId: this.article?.category_id || this.article?.categoryId,
					size: 5
				};
				const res = await articleApi.getList(params);
				
				
				if (res.code === 200) {
					// 过滤掉当前文章
					const allArticles = res.data.rows || [];
					this.recommendArticles = allArticles.filter(item => item.id !== this.article.id).slice(0, 5);
				} else {
					console.error('[详情页] 推荐文章API返回错误:', res.code, res.msg);
				}
			} catch (error) {
				console.error('[详情页] 推荐文章加载失败:', error);
				console.error('[详情页] 推荐文章加载错误堆栈:', error.stack);
			}
		},
		
		retry() {
			this.error = '';
			if (this.article?.id) {
				this.loadArticleDetail(this.article.id);
			}
		},
		
		goDetail(item) {
			uni.navigateTo({
				url: `/pages/detail/detail?id=${item.id}`
			});
		},
		
		getFirstImage(images) {
			if (!images) return '';
			try {
				// 空数组字符串直接返回空
				if (typeof images === 'string' && images.trim() === '[]') return '';
				let imageList = images;
				if (typeof images === 'string') {
					const cleanStr = images.replace(/\\/g, '');
					imageList = JSON.parse(cleanStr);
				}
				if (Array.isArray(imageList) && imageList.length > 0) {
					const firstImage = imageList[0];
					let imageUrl = '';
					if (typeof firstImage === 'object' && firstImage.url) {
						imageUrl = firstImage.url;
					} else if (typeof firstImage === 'string') {
						imageUrl = firstImage;
					}
					if (imageUrl) {
						return getFullImageUrl(imageUrl);
					}
				}
				return '';
			} catch (error) {
				return '';
			}
		},
		
		getImageUrl(url) {
			return getFullImageUrl(url);
		},
		
		previewImage(images, currentIndex) {
			const urls = images.map(img => this.getImageUrl(img.url || img));
			uni.previewImage({
				urls: urls,
				current: urls[currentIndex],
				loop: true,
				indicator: 'number'
			});
		},
		
		onSwiperChange(e) {
			this.current = e.detail.current;
		},
		
		formatDate(dateStr) {
			if (!dateStr) return '';
			try {
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			} catch (error) {
				return dateStr;
			}
		},
		
		onImageError(e) {
			console.error('图片加载失败:', e);
		},

		toggleRenderMode() {
			this.useTemplateRender = !this.useTemplateRender;
		}
	}
}
</script>
<style lang="scss" scoped>
.container {
	padding: 15px;
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 模板内容样式 */
.template-content {
	width: 100%;
	height: 100%;
	overflow-y: auto;
}

.top-swiper-wrap {
	position: relative;
	margin-bottom: 16px;
}
.top-swiper {
	width: 100%;
	height: 400rpx;
}
.swiper-image {
	width: 100%;
	height: 400rpx;
	border-radius: 12rpx;
}
.img-count {
	position: absolute;
	right: 24rpx;
	bottom: 16rpx;
	color: #fff;
	background: rgba(0,0,0,0.4);
	border-radius: 20rpx;
	padding: 4rpx 12rpx;
	font-size: 24rpx;
}

.article-header {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 10px;
	
	.article-title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
		line-height: 1.4;
		margin-bottom: 10px;
	}
	
	.article-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		
		.meta-item {
			font-size: 12px;
			color: #999;
		}
	}
}

.article-desc {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 10px;
	
	.desc-text {
		font-size: 14px;
		color: #666;
		line-height: 1.5;
	}
}

.image-list {
	margin-top: 20rpx;
	.list-image {
		width: 100%;
		margin-bottom: 16rpx;
		border-radius: 12rpx;
	}
}

.article-content {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 10px;
	
	.content-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
	}
	
	.content-text {
		font-size: 14px;
		color: #333;
		line-height: 1.6;
	}
}

.recommend-section {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 10px;
	
	.section-title {
		margin-bottom: 15px;
		
		.title-text {
			font-size: 16px;
			font-weight: bold;
			color: #333;
		}
	}
	
	.recommend-list {
		.recommend-item {
			display: flex;
			padding: 10px 0;
			border-bottom: 1px solid #f0f0f0;
			
			&:last-child {
				border-bottom: none;
			}
			
			.recommend-image {
				width: 80px;
				height: 60px;
				border-radius: 6px;
				margin-right: 10px;
			}
			
			.recommend-info {
				flex: 1;
				
				.recommend-title {
					font-size: 14px;
					color: #333;
					line-height: 1.4;
					margin-bottom: 5px;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
				
				.recommend-desc {
					font-size: 12px;
					color: #999;
					line-height: 1.3;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
			}
		}
	}
}

.loading, .empty-state {
	padding: 16px 0;
	text-align: center;
}

.loading-text, .empty-text {
	font-size: 14px;
	color: #999;
}

.error-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100vh;
	padding: 20px;
}

.error-text {
	font-size: 16px;
	color: #666;
	margin-bottom: 20px;
	text-align: center;
}

.retry-btn {
	padding: 12px 24px;
	background-color: #007aff;
	color: #fff;
	border-radius: 6px;
	font-size: 16px;
}

.share-btn-wrap {
	display: flex;
	justify-content: center;
	margin: 24px 0 0 0;
}
.share-btn {
	background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
	color: #fff;
	font-size: 16px;
	border-radius: 24px;
	padding: 0 32px;
	height: 48px;
	line-height: 48px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
</style>
